{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "fiscal-arctic",
   "metadata": {},
   "source": [
    "**This is example of how to trace model with jit and export it to the onnx**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "impressed-toolbox",
   "metadata": {},
   "outputs": [],
   "source": [
    "from rl_games.torch_runner import Runner\n",
    "import ray\n",
    "import yaml\n",
    "import torch\n",
    "import matplotlib.pyplot as plt\n",
    "import gym\n",
    "from IPython import display\n",
    "import numpy as np\n",
    "import onnx\n",
    "import onnxruntime as ort\n",
    "%matplotlib inline"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "unexpected-grenada",
   "metadata": {},
   "outputs": [],
   "source": [
    "ray.init(object_store_memory=1024*1024*1000)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "hazardous-closing",
   "metadata": {},
   "outputs": [],
   "source": [
    "config_name = 'rl_games/configs/ppo_cartpole.yaml'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "wired-token",
   "metadata": {},
   "outputs": [],
   "source": [
    "with open(config_name, 'r') as stream:\n",
    "    config = yaml.safe_load(stream)\n",
    "    config['params']['config']['full_experiment_name'] = 'cartpole_onnx'\n",
    "runner = Runner()\n",
    "runner.load(config)\n",
    "runner.run({\n",
    "    'train': True,\n",
    "})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "social-separation",
   "metadata": {},
   "outputs": [],
   "source": [
    "agent = runner.create_player()\n",
    "agent.restore('runs/cartpole_onnx/nn/cartpole_vel_info.pth')\n",
    "\n",
    "import rl_games.algos_torch.flatten as flatten\n",
    "inputs = {\n",
    "    'obs' : torch.zeros((1,) + agent.obs_shape).to(agent.device),\n",
    "    'rnn_states' : agent.states\n",
    "}\n",
    "with torch.no_grad():\n",
    "    adapter = flatten.TracingAdapter(agent.model.a2c_network, inputs,allow_non_tensor=True)\n",
    "    traced = torch.jit.trace(adapter, adapter.flattened_inputs,check_trace=False)\n",
    "    flattened_outputs = traced(*adapter.flattened_inputs)\n",
    "    print(flattened_outputs)\n",
    "    \n",
    "torch.onnx.export(traced, *adapter.flattened_inputs, \"cartpole.onnx\", verbose=True, input_names=['obs'], output_names=['logits', 'value'])\n",
    "\n",
    "onnx_model = onnx.load(\"cartpole.onnx\")\n",
    "\n",
    "# Check that the model is well formed\n",
    "onnx.checker.check_model(onnx_model)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "prospective-inspection",
   "metadata": {},
   "outputs": [],
   "source": [
    "ort_model = ort.InferenceSession(\"cartpole.onnx\")\n",
    "\n",
    "outputs = ort_model.run(\n",
    "    None,\n",
    "    {\"obs\": np.zeros((1, 4)).astype(np.float32)},\n",
    ")\n",
    "print(outputs)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "social-trash",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "professional-deadline",
   "metadata": {},
   "outputs": [],
   "source": [
    "is_done = False\n",
    "env = agent.env\n",
    "obs = env.reset()\n",
    "#prev_screen = env.render(mode='rgb_array')\n",
    "#plt.imshow(prev_screen)\n",
    "total_reward = 0\n",
    "num_steps = 0\n",
    "while not is_done:\n",
    "    outputs = ort_model.run(None, {\"obs\": np.expand_dims(obs, axis=0).astype(np.float32)},)\n",
    "    action = np.argmax(outputs[0])\n",
    "    obs, reward, done, info = env.step(action)\n",
    "    total_reward += reward\n",
    "    num_steps += 1\n",
    "    is_done = done\n",
    "    screen = env.render(mode='rgb_array')\n",
    "    #plt.imshow(screen)\n",
    "    #display.display(plt.gcf())    \n",
    "    #display.clear_output(wait=True)\n",
    "print(total_reward, num_steps)\n",
    "#ipythondisplay.clear_output(wait=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "charitable-sculpture",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.9"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
